﻿/* ************************************************************************************* 
 * CREATED BY:          CUNG MANH GIAP
 * CREATED DATE:        05/01/2009
 * PROJECT:             MCEnterpriseWebsite PROJECT
 * PURPOSE:             
 * MODIFIED BY:         None
 * MODIFIED DATE:       None
 * MODIFIED REASON:     None
 * NOTES:               None
 **************************************************************************************/

using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
using MCWEBSITE.BUL;
using MCWEBSITE.ENTITY;
using MCWF;

public partial class Modules_WebsiteFrontEnd_wucNewsDetail : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string[] ResourceDirectory = { "" };
        ResourceDirectory[0] = lblResourceDirectoryTemp.Text.Trim();
        this.SetEditorParameters(ResourceDirectory);
    }

    #region "UTILITIES"

    //SET PAPAMETERS FOR RAD EDITOR
    public void SetEditorParameters(string[] UploadDir)
    {
        //SET IMAGE MANAGER PATHS
        redtContentText.ImageManager.MaxUploadFileSize = 20971520; //20MB
        redtContentText.ImageManager.DeletePaths = UploadDir;
        redtContentText.ImageManager.ViewPaths = UploadDir;
        redtContentText.ImageManager.UploadPaths = UploadDir;

        //SET MEDIA MANAGER PATHS
        redtContentText.MediaManager.MaxUploadFileSize = 41943040; //40MB
        redtContentText.MediaManager.ViewPaths = UploadDir;
        redtContentText.MediaManager.UploadPaths = UploadDir;
        redtContentText.MediaManager.DeletePaths = UploadDir;

        //SET FLASH MANAGER PATHS
        redtContentText.FlashManager.MaxUploadFileSize = 41943040; //40MB
        redtContentText.FlashManager.ViewPaths = UploadDir;
        redtContentText.FlashManager.UploadPaths = UploadDir;
        redtContentText.FlashManager.DeletePaths = UploadDir;

        redtContentText.DocumentManager.MaxUploadFileSize = 41943040; //40MB
        redtContentText.DocumentManager.ViewPaths = UploadDir;
        redtContentText.DocumentManager.UploadPaths = UploadDir;
        redtContentText.DocumentManager.DeletePaths = UploadDir;
    }

    #endregion

    #region "BINDING DATA CONTROLS"

    public void BindDataControl()
    {
        this.BindLanguage();
        this.BindCategories();
    }

    public void BindLanguage()
    {
        List<websiteLanguageInfo> objLanguage = websiteLanguageBUL.GetAll();
        rcbLanguage.DataSource = objLanguage;
        rcbLanguage.DataValueField = "LanguageCode";
        rcbLanguage.DataTextField = "languageName";
        rcbLanguage.DataBind();
    }

    public void BindCategories()
    {
        List<websiteNewsCategoryInfo> objCat = websiteNewsCategoryBUL.GetAll();
        rcbCategories.DataSource = objCat;
        rcbCategories.DataValueField = "CategoryID";
        rcbCategories.DataTextField = "CategoryName";
        rcbCategories.DataBind();
    }

    protected void BindDataDetail(int ItemID)
    {
        string[] ResourceDirectory = { "" };
        if (ItemID != -1)
        {
            // Bind news infor
            websiteNewsInfo objNews = websiteNewsBUL.Load(ItemID);
            lblNewsID.Text = Convert.ToString(objNews.NewsID);
            rdtpCreateDate.SelectedDate = objNews.CreatDate;
            tbTitle.Text = Utilities.ConvertToUnicode(objNews.Tittle);
            tbSummary.Text = Utilities.ConvertToUnicode(objNews.Summary);
            redtContentText.Content = objNews.NewsContent;
            rcbLanguage.Items.FindItemByValue(Convert.ToString(objNews.LanguageCode)).Selected = true;
            rcbCategories.Items.FindItemByValue(Convert.ToString(objNews.CategoryID)).Selected = true;
            // Check resource directory
            ResourceDirectory[0] = objNews.Image;
            string ResourcePhysicalPath = Server.MapPath(ResourceDirectory[0]);
            DirectoryInfo ResourcePhysicalDir = new DirectoryInfo(ResourcePhysicalPath);
            if (!ResourcePhysicalDir.Exists)
            {
                ResourcePhysicalDir.Create();
            }
            lblResourceDirectoryTemp.Text = objNews.Image;
            // Check thumb directory
            string ThumbDirectory = objNews.Image + "thumbimg/";
            string ThumbPhysicalPath = Server.MapPath(ThumbDirectory);
            DirectoryInfo ThumbPhysicalDir = new DirectoryInfo(ThumbPhysicalPath);
            if (!ThumbPhysicalDir.Exists)
                ThumbPhysicalDir.Create();
            lblThumbDirectoryTemp.Text = objNews.Image + "thumbimg/";
            // Assign parameter for RadUpload and RadEditor
            this.SetEditorParameters(ResourceDirectory);
        }
        else
        {
            lblNewsID.Text = "";
            rdtpCreateDate.SelectedDate = DateTime.Now;
            tbTitle.Text = "";
            tbSummary.Text = "";
            redtContentText.Content = "";
            // Resources directory
            ResourceDirectory[0] = "~/Resources/NewsImages/temp";
            string TempDirectory = "";
            string ThumbPhysicalPath = "";
            string ThumbDirectory = "";
            if (lblResourceDirectoryTemp.Text == "" && lblThumbDirectoryTemp.Text == "")
            {
                for (int i = 1; i <= 200; i++)
                {
                    TempDirectory = Server.MapPath(ResourceDirectory[0]);
                    TempDirectory = TempDirectory + "\\" + i.ToString() + "\\";
                    DirectoryInfo ResourcePhysicalDirectory = new DirectoryInfo(TempDirectory);
                    if (!ResourcePhysicalDirectory.Exists)
                    {
                        // Create resource directory
                        ResourcePhysicalDirectory.Create();
                        ResourceDirectory[0] = ResourceDirectory[0] + "\\" + ResourcePhysicalDirectory.Name;
                        ThumbDirectory = ResourceDirectory[0] + "\\" + "thumbimg";
                        // Create resource thumb directory ThumbDir = UploadDir[0] + "/" + "thumbimg";
                        ThumbPhysicalPath = Server.MapPath(ResourceDirectory[0] + "\\" + "thumbimg");
                        DirectoryInfo ThumbPhysicalDirectory = new DirectoryInfo(ThumbPhysicalPath);
                        if (!ThumbPhysicalDirectory.Exists)
                        {
                            ThumbPhysicalDirectory.Create();
                        }
                        // Assign temp directory to label
                        lblResourceDirectoryTemp.Text = ResourceDirectory[0];
                        lblThumbDirectoryTemp.Text = ThumbDirectory;
                        break;
                    }
                }
            }
            else
            {
                ResourceDirectory[0] = lblResourceDirectoryTemp.Text;
            }
            // Assign parameter for RadEditor
            this.SetEditorParameters(ResourceDirectory);
        }
    }

    #endregion

    #region "DATA HANDLING PROCEDURE/FUNCTION"

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    protected int InsertRow(NewsToolbarButton ClickedButton)
    {       
        websiteNewsInfo objNews = new websiteNewsInfo();
        objNews.NewsID = 0;
        objNews.Tittle = tbTitle.Text.Trim();
        objNews.Summary = tbSummary.Text.Trim();
        objNews.NewsContent = redtContentText.Content.Trim();
        objNews.CreatDate = rdtpCreateDate.SelectedDate.Value;
        objNews.Creater = HttpContext.Current.User.Identity.Name;
        objNews.LanguageCode = rcbLanguage.SelectedValue;
        objNews.CategoryID = Convert.ToInt32(rcbCategories.SelectedValue);
        // Build ActionCode      
        // Perform save action
        try
        {
            // Save news object
            int InsertedNewsId = websiteNewsBUL.Save(objNews);
            // Moving all resource from temp directory to newly created one
            // Get CreateDate from database based on NewsId
            string CreateDate = websiteNewsBUL.GetCreateDate(InsertedNewsId);
            string ResourceDirectory = "~/Resources/NewsImages/" + CreateDate + "/" + InsertedNewsId.ToString() + "/";
            string ThumbDirectory = ResourceDirectory + "thumbimg/";
            // Insert NewsThumbImg object to NewsThumbImg table
            websiteNewsBUL.InsertResource(InsertedNewsId, ResourceDirectory);
            // Processing resource 
            // Create resource directory and thumb directory approximately
            DirectoryInfo ResourcesDir = new DirectoryInfo(Server.MapPath(ResourceDirectory));
            if (!ResourcesDir.Exists) ResourcesDir.Create();
            DirectoryInfo ThumbDir = new DirectoryInfo(Server.MapPath(ThumbDirectory));
            if (!ThumbDir.Exists) ThumbDir.Create();
            // Copy all resource from temp directory to newly created one
            Utilities.CopyDirectory(Server.MapPath(lblResourceDirectoryTemp.Text), Server.MapPath(ResourceDirectory), true);
            // Delete temp directory
            DirectoryInfo TempDir = new DirectoryInfo(Server.MapPath(lblResourceDirectoryTemp.Text));
            TempDir.Delete(true);
            // Update resource path in contenttext
            objNews.NewsID = InsertedNewsId;
            websiteNewsBUL.SaveComposeResource(objNews, HttpContext.Current.Request.ApplicationPath.Substring(1, Request.ApplicationPath.Length - 1));

            // Return result
            return 1;
        }
        catch
        {
            return -1;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    protected int DeleteRow()
    {
        websiteNewsInfo objNews = websiteNewsBUL.Load(Convert.ToInt32(lblNewsID.Text));
        // Delete Resource directory
        DirectoryInfo ResourceDirectory = new DirectoryInfo(Server.MapPath(objNews.Image));
        if (ResourceDirectory.Exists)
            ResourceDirectory.Delete(true);
        // Delete News object
        return websiteNewsBUL.Remove(Convert.ToInt32(lblNewsID.Text.Trim()));
    }

    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    protected int UpdateRow(NewsToolbarButton ClickedButton)
    {      
        websiteNewsInfo objNews = new websiteNewsInfo();
        objNews.NewsID = Convert.ToInt32(lblNewsID.Text);
        objNews.Tittle = tbTitle.Text.Trim();
        objNews.Summary = tbSummary.Text.Trim();
        objNews.NewsContent = redtContentText.Content.Trim();
        objNews.CreatDate = rdtpCreateDate.SelectedDate.Value;
        objNews.LanguageCode = rcbLanguage.SelectedValue;
        objNews.CategoryID = Convert.ToInt32(rcbCategories.SelectedValue);
        // Perform save action
        try
        {
            // Save news object
            if (ClickedButton == NewsToolbarButton.SAVEBUTTON)
            {
                objNews.IsActive = websiteNewsBUL.Load(Convert.ToInt32(lblNewsID.Text)).IsActive;
                return websiteNewsBUL.Save(objNews);
            }
            else
            {
                objNews.IsActive = true;
                return websiteNewsBUL.Save(objNews);
            }
        }
        catch
        {
            return -1;
        }
    }

    #endregion

    #region "PUBLIC PROCEDURE/FUNCTION"
    /// <summary>
    /// 
    /// </summary>
    /// <param name="ClickedButton"></param>
    /// <returns></returns>   
    public string PerformToolbarEvent(NewsToolbarButton ClickedButton)
    {
        string ResultString = "";
        int ReturnResult;

        // Create a new news and save OR create a new news and submit
        if (lblCurrentMode.Text.ToString().ToUpper() == NewsToolbarStatus.NEW.ToString().ToUpper() &&
            (ClickedButton == NewsToolbarButton.SAVEBUTTON || ClickedButton == NewsToolbarButton.SUBMITBUTTON))
        {
            if (Page.IsValid)
            {
                ReturnResult = this.InsertRow(ClickedButton);
                lblResourceDirectoryTemp.Text = "";
                lblThumbDirectoryTemp.Text = "";
                if ((int)ReturnResult > 0) ResultString = "Bản ghi được bổ xung thành công";
                else ResultString = "Lỗi trong quá trình bổ xung bản ghi";
            }
        }

        // Edit a news and save OR Edit a news and submit
        if (lblCurrentMode.Text.ToString().ToUpper() == NewsToolbarStatus.EDIT.ToString().ToUpper() &&
            (ClickedButton == NewsToolbarButton.SAVEBUTTON || ClickedButton == NewsToolbarButton.SUBMITBUTTON))
        {
            if (Page.IsValid)
            {
                ReturnResult = this.UpdateRow(ClickedButton);
                lblResourceDirectoryTemp.Text = "";
                lblThumbDirectoryTemp.Text = "";
                if ((int)ReturnResult > 0) ResultString = "Bản ghi được cập nhật thành công";
                else ResultString = "Lỗi trong quá trình cập nhật bản ghi";
            }
        }

        // Edit a news and delete
        if (lblCurrentMode.Text.ToString().ToUpper() == NewsToolbarStatus.EDIT.ToString().ToUpper() &&
            ClickedButton == NewsToolbarButton.DELBUTTON)
        {
            ReturnResult = this.DeleteRow();
            lblResourceDirectoryTemp.Text = "";
            lblThumbDirectoryTemp.Text = "";
            if ((int)ReturnResult > 0) ResultString = "Bản ghi được xóa thành công";
            else ResultString = "Lỗi trong quá trình xóa bản ghi";
        }
        //Modify by Huyenmt
        //Upload News Image
        if (ClickedButton == NewsToolbarButton.IMAGEBUTTON)
        {
            // Show upload images windows
            ThumbUploadWindow.NavigateUrl = "~/Default.aspx?Page=thumbupload&ResourceDir=" + lblResourceDirectoryTemp.Text + "&ThumbDir=" + lblThumbDirectoryTemp.Text;
            ThumbUploadWindow.VisibleOnPageLoad = true;
        }

        // Coding by Huyenmt
        //Preview a news
        if (ClickedButton == NewsToolbarButton.PREVIEWBUTTON)
        {

            websiteNewsInfo objNews = new websiteNewsInfo();
            if (lblCurrentMode.Text.ToString().ToUpper() == NewsToolbarStatus.NEW.ToString().ToUpper())
            {
                objNews.NewsID = 0;
            }
            else
            {
                objNews.NewsID = Convert.ToInt32(lblNewsID.Text);
            }
            objNews.Tittle = tbTitle.Text;
            objNews.Summary = tbSummary.Text;
            objNews.NewsContent = redtContentText.Content;
            Session["CurrentNews"] = objNews;
            //View Preview popup
            PreviewWindow.NavigateUrl = "~/Default.aspx?page=newspreview&Thumbdir=" + lblResourceDirectoryTemp.Text.Trim();
            PreviewWindow.VisibleOnPageLoad = true;
            ResultString = "Thực hiện chỉnh sửa và lưu bản ghi hoặc bấm undo để trở lại";
        }
        // Coding by Huyenmt
        // Undo
        if (lblCurrentMode.Text.ToString().ToUpper() == NewsToolbarStatus.EDIT.ToString().ToUpper() &&
            ClickedButton == NewsToolbarButton.UNDOBUTTON)
        {
            ResultString = "LỰA CHỌN TÁC VỤ TRÊN THANH CÔNG CỤ";
            if (lblCurrentMode.Text.ToString().ToUpper() == NewsToolbarStatus.NEW.ToString().ToUpper())
            {
                DirectoryInfo ResourceDirectoryInfo = new DirectoryInfo(Server.MapPath(lblResourceDirectoryTemp.Text));
                if (ResourceDirectoryInfo.Exists)
                    ResourceDirectoryInfo.Delete(true);
            }
        }
        return ResultString;
    }


    public void SetControlMode(NewsToolbarStatus ToolbarMode)
    {
        if (ToolbarMode == NewsToolbarStatus.NEW)
        {
            lblDetailMode.Text = "TẠO MỚI BẢN GHI";
            lblCurrentMode.Text = NewsToolbarStatus.NEW.ToString().ToUpper();
        }
        if (ToolbarMode == NewsToolbarStatus.EDIT)
        {
            lblDetailMode.Text = "CHỈNH SỬA BẢN GHI";
            lblCurrentMode.Text = NewsToolbarStatus.EDIT.ToString().ToUpper();
        }
    }

    public void SetDetailData(int ItemID)
    {
        this.BindDataControl();
        this.BindDataDetail(ItemID);
    }

    public void RefreshDetailView()
    {
        if (lblCurrentMode.Text.ToString().ToUpper() == NewsToolbarStatus.NEW.ToString().ToUpper())
        {
            this.BindDataDetail(-1);
        }
        else
        {
            int SelectedItemID = Convert.ToInt32(lblNewsID.Text.Trim());
            this.BindDataDetail(SelectedItemID);
        }
    }

    #endregion
}
